const axios = require("axios");

const port = 3000;

const instance = axios.create({
    baseURL: `http://localhost:${port}`,
    timeout: 5000,
    headers: { 'X-Custom-Header': 'foobar' }
});

function sendRequest(url, method, data) {
    return new Promise((resolve,reject)=>{
        instance({
            url,
            method,
            data: method === 'get' ? {} : data
        }).then(response => {
            resolve(response)
        }).catch(err =>{
            reject(err)
        })
    })
}

// 创建 POST 请求
function post(url, data) {
   return sendRequest(url, 'post', data);
}

// 创建 DELETE 请求
function del(url, data) {
    return sendRequest(`${url}/${data.id}`, 'delete', data);
}

// 创建 PUT 请求
function put(url, data) {
    return sendRequest(`${url}/${data.id}`, 'put', data);
}

// 创建 GET 请求
function get(url) {
    return sendRequest(url, 'get');
}

module.exports = {
    post,
    del,
    put,
    get,
    port
}